package chapter7_取消关闭.中断取消;

import annotation.GuardedBy;
import annotation.ThreadSafe;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 分析：通过在单次循环前，对volatile修饰的取消标志位赋值，来进行任务取消
 */
@ThreadSafe
public class PrimeGenerator implements Runnable {
    @GuardedBy("this")
    private final List<BigInteger> primes = new ArrayList<>();

    @Override
    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!Thread.currentThread().isInterrupted()) {
            p = p.nextProbablePrime();
            synchronized (this) {
                primes.add(p);
            }
        }
    }

    public void cancel() {
        Thread.currentThread().interrupt();
    }

    public synchronized List<BigInteger> get() {
        //拷贝一个副本，而不是直接把primes发布出去
        return new ArrayList<>(primes);
    }



}
